'use strict'

const { ApiController } = require('jax')

class Controller extends ApiController {
  get Model() {
    return this.ctx.model.Store
  }

  // 匹配查询
  get searchKey() {
    return ['isOpen', 'category']
  }

  // 模糊查询
  get likeKey() {
    return ['deviceName', 'deviceTypeName']
  }

  // 查询前
  async beforeIndex() {
    const { ctx } = this
    const { query } = ctx
    const { helper } = ctx
    const filter = {}

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') {
      const reg = new RegExp(helper.toMongoRegex(query.keyword, 'i'))
      filter.$or = [{ storeName: reg }]
    }

    return {
      filter,
    }
  }

  // 格式化
  async formatData(item) {
    delete item.password
  }

  // 新增前
  async beforeCreate() {
    const { ctx } = this
    const { body } = ctx.request
    const { ADMIN_PASSWORD } = this.config.constant

    // 默认密码
    if (!body.password) body.password = ADMIN_PASSWORD
  }

  // 保存前
  async beforeSave() {
    const { ctx } = this
    const { helper } = ctx
    const { body } = ctx.request

    // 账户校验
    if (body.username && body.username != '')
      await ctx.service.systemUser.verifyUsername(body.username, body.adminId)

    // 手机号校验
    if (body.mobile && body.mobile != '') await ctx.service.systemUser.verifyMobile(body.mobile, body.adminId)

    // 密码MD5
    if (body.password) body.password = helper.md5(body.password)

    // 地址
    if (body.province) body.address = body.province + body.city + body.district + body.detaileAddress

    if (!body.appKey || body.appKey == '') body.appKey = helper.nonceStr(16)
    if (!body.appSecret || body.appSecret == '') body.appSecret = helper.nonceStr(30)
  }

  // 保存后
  async afterSave(store) {
    const { ctx } = this
    const { body } = ctx.request

    await this.updateAccount(store)
  }

  // 更新账号
  async updateAccount(store) {
    const { ctx } = this
    const { md5 } = ctx.helper
    const { SYSTEM_TYPE_STORE, ADMIN_PASSWORD } = this.config.constant

    const adminRole = await ctx.model.AdminRole.findOne({
      systemType: SYSTEM_TYPE_STORE,
      isAdmin: true,
    })

    if (!adminRole) throw '未配置角色'

    // 未配置账号
    if (!store.mobile) {
      // 移除账号
      if (store.adminId) {
        await ctx.model.Admin.deleteOne({ _id: store.adminId })
        store.adminId = null
        store.password = null
        await store.save()
      }

      return
    }

    const adminData = {
      systemType: adminRole.systemType,
      roleId: adminRole._id,
      sourceId: store._id,
      sourceType: SYSTEM_TYPE_STORE,
      source: { storeId: store._id },

      username: store.username,
      mobile: store.mobile,
      password: store.password,

      isSystem: true,
      isOpen: store.isOpen,
    }

    if (store.adminId) {
      await ctx.model.Admin.updateOne({ _id: store.adminId }, adminData)
    } else {
      const admin = await ctx.model.Admin.create({
        ...adminData,
        password: md5(ADMIN_PASSWORD),
      })
      store.adminId = admin._id
      await store.save()
    }
  }

  // 门店信息
  async getStoreInfo() {
    const { ctx } = this
    const { helper } = ctx
    const { admin } = ctx.state

    const store = await ctx.model.Store.findOne({
      _id: admin.sourceId,
    })

    ctx.body = {
      code: 0,
      data: helper.exclude(store, ['password', 'createdAt', 'updatedAt', 'isDelete']),
    }
  }

  // 修改门店信息
  async setStoreInfo() {
    const { ctx } = this
    const { helper } = ctx
    const { body } = ctx.request
    const { admin } = ctx.state

    const store = await ctx.model.Store.findOne({
      _id: admin.sourceId,
    })

    const data = helper.exclude(body, [
      'id',
      '_id',
      'username',
      'password',
      'canCustom',
      'createdAt',
      'updatedAt',
    ])

    // 地址
    if (data.province) data.address = data.province + data.city + data.district + data.detaileAddress

    await ctx.model.Store.updateOne(
      {
        _id: store.id,
      },
      data
    )

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }
}

module.exports = Controller
